package com.stylefeng.guns.modular.system.controller;

import com.stylefeng.guns.common.annotion.log.BussinessLog;
import com.stylefeng.guns.common.constant.Dict;
import com.stylefeng.guns.common.controller.BaseController;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.OrgClassMapper;
import com.stylefeng.guns.common.persistence.dao.OrgClassTypeMapper;
import com.stylefeng.guns.common.persistence.dao.OrgInfoMapper;
import com.stylefeng.guns.common.persistence.dao.OrgTeacherMapper;
import com.stylefeng.guns.common.persistence.model.OrgClass;
import com.stylefeng.guns.common.persistence.model.OrgClassType;
import com.stylefeng.guns.common.persistence.model.OrgInfo;
import com.stylefeng.guns.common.persistence.model.OrgTeacher;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.modular.system.dao.OrgClassTypeDao;
import com.stylefeng.guns.modular.system.dao.OrgTeacherDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 教师管理控制器
 *
 * @author fengshuonan
 * @Date 2018-08-20 10:50:28
 */
@Controller
@RequestMapping("/orgTeacher")
public class OrgTeacherController extends BaseController {

    private String PREFIX = "/system/orgTeacher/";

    @Autowired
    OrgTeacherMapper orgTeacherMapper;
    @Autowired
    OrgClassMapper orgClassMapper;
    @Autowired
    OrgInfoMapper orgInfoMapper;
    @Autowired
    OrgClassTypeMapper orgClassTypeMapper;
    @Autowired
    OrgClassTypeDao orgClassTypeDao;
    @Autowired
    CheckAccessUtil checkAccessUtil;
    @Autowired
    OrgTeacherDao orgTeacherDao;

    @Resource
    private GunsProperties gunsProperties;

    /**
     * 跳转到教师管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "orgTeacher.html";
    }

    /**
     * 跳转到添加教师管理
     */
    @RequestMapping("/orgTeacher_add")
    public String orgTeacherAdd() {
        return PREFIX + "orgTeacher_add.html";
    }

    @RequestMapping("/orgTeacher_admin_add")
    public String orgTeacherAdminAdd() {
        return PREFIX + "orgTeacher_admin_add.html";
    }

    /**
     * 跳转到修改教师管理
     */
    @RequestMapping("/orgTeacher_update/{orgTeacherId}")
    public String orgTeacherUpdate(@PathVariable Integer orgTeacherId, Model model) {
        OrgTeacher old=this.orgTeacherMapper.selectById(orgTeacherId);

        OrgInfo orgInfos = orgInfoMapper.selectById(old.getInfoId());
        old.setInfoName(orgInfos.getOrgName());
        List<String>  classIds = Arrays.asList(old.getClassId().split(","));
        String classNames = "";
        for (String id:classIds) {
            try{
                OrgClassType orgClassType = orgClassTypeMapper.selectById(id);
                classNames += orgClassType.getClassName()+',';
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if( "" != classNames){
            classNames = classNames.substring(0, classNames.length() - 1);
        }
        String sex = old.getTeacherSex();
        Integer a = Integer.valueOf(sex);
        if(a == 1){
            old.setTeacherSexName("男");
        }else if(a == 2){
            old.setTeacherSexName("女");
        }else {
            old.setTeacherSexName("兔子跑了");
        }
        old.setClassName(classNames);
        model.addAttribute("orgTeacher",old);

        return PREFIX + "orgTeacher_edit.html";
    }
    @RequestMapping("/orgTeacher_particulars/{orgTeacherId}")
    public String orgTeacherParticulars(@PathVariable Integer orgTeacherId,Model model){
        OrgTeacher old=this.orgTeacherMapper.selectById(orgTeacherId);
        OrgInfo orgInfos = orgInfoMapper.selectById(old.getInfoId());
        old.setInfoName(orgInfos.getOrgName());
        List<String>  classIds = Arrays.asList(old.getClassId().split(","));
        String classNames = "";
        for (String id:classIds) {
            try{
                OrgClassType orgClassType = orgClassTypeMapper.selectById(id);
                classNames += orgClassType.getClassName()+',';
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if( "" != classNames){
            classNames = classNames.substring(0, classNames.length() - 1);
        }
        old.setClassId(classNames);
        String sex = old.getTeacherSex();
        Integer a = Integer.valueOf(sex);
        if(a == 1){
            old.setTeacherSexName("男");
        }else if(a == 2){
            old.setTeacherSexName("女");
        }else {
            old.setTeacherSexName("兔子跑了");
        }
        model.addAttribute("orgTeacher",old);
        return PREFIX + "orgTeacher_particulars.html";
    }
    /**
     * 选择课程
     */
    @RequestMapping(value = "/chooseClass")
    public Object chooseClass(Integer type) {
        //1表示单选
        if(2==type){
            return PREFIX + "kid2.html";
        }
        return PREFIX + "kid1.html";
    }

    /**
     *  如果返回 -1 表示 userId 不存在 即info_id 不存在
     *  如果返回 0 则表示要查询所有 数据
     *  如果返回 不等于0  则返回值为 jinfo_id
     *
     * 获取教师管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list() {
        //创建List对象容器
        List<OrgTeacher> orgTeachers = null;
        //获取权限监测返回值
           int infoId =  checkAccessUtil.CheckAccess();
        //  如果返回 -1 表示 userId 不存在 即info_id 不存在
        //  如果返回 0 则表示要查询所有 数据
        //  如果返回 不等于0  则返回值为 info_id
        if(infoId == 0){
            //查询所有对象列表
            orgTeachers = orgTeacherMapper.selectList(null);
        }else if(infoId == -1){
           return null;
        }else{
           //根据infoId 去找到对象信息
           orgTeachers = orgTeacherDao.findByInfoId(infoId);
        }

        for(OrgTeacher orgTeacher:orgTeachers){
            String sexName1 = "男";
            String sexName2 = "女";
            String teacherSex = orgTeacher.getTeacherSex();
            int sex = Integer.valueOf(teacherSex);
            if(sex == 1){
                orgTeacher.setTeacherSexName(sexName1);
            }else{
                orgTeacher.setTeacherSexName(sexName2);
            }
        }
        for (OrgTeacher orgTeacher:orgTeachers) {
            List<String>  classIds = Arrays.asList(orgTeacher.getClassId().split(","));
            String classNames = "";
            for (String id:classIds) {
                try{
                    OrgClassType orgClassType = orgClassTypeMapper.selectById(id);
                    classNames += orgClassType.getClassName()+',';
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if( "" != classNames){
                classNames = classNames.substring(0, classNames.length() - 1);
            }
            orgTeacher.setClassId(classNames);
        }
        for (OrgTeacher orgTeacher:orgTeachers){
            String infoIds = orgTeacher.getInfoId();
            OrgInfo orgInfo = orgInfoMapper.selectById(infoIds);
            if (orgInfo != null){
                String infoNames = "";
                infoNames = orgInfo.getOrgName();
                orgTeacher.setInfoId(infoNames);
            }
        }

        return orgTeachers;
    }


    /**
     * 选择课程列表数据
     */
    @RequestMapping(value = "/chooseClassList")
    @ResponseBody
    public Object chooseClassList() {
        List<OrgClassType> orgClassTypeList = orgClassTypeDao.findAll();
        return orgClassTypeList;
    }

    /**
     * 新增教师管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(OrgTeacher orgTeacher) {
        if(orgTeacher !=null){
            orgTeacher.setCreateDate(new Date());
        }
        int infoId =  checkAccessUtil.CheckAccess();
        if(infoId == -1){
            return null;
        }else if(infoId == 0){

        }else{
            String infoIds = String.valueOf(infoId);
            orgTeacher.setInfoId(infoIds);
        }
        orgTeacher.setClassId("1");
        orgTeacher.setPath("D:/MyProjectName/UploadData/images");
        Integer insert = orgTeacherMapper.insert(orgTeacher);
        return super.SUCCESS_TIP;
    }

    /**
     * 管理员新增教师管理
     */
    @RequestMapping(value = "/addAdmin")
    @ResponseBody
    public Object addAdmin(OrgTeacher orgTeacher) {
        if(orgTeacher !=null){
            orgTeacher.setCreateDate(new Date());
        }
        orgTeacher.setPath("D:/MyProjectName/UploadData/images");
        orgTeacher.setClassId("1");
        Integer insert = orgTeacherMapper.insert(orgTeacher);
        return super.SUCCESS_TIP;
    }


    /**
     * 删除教师管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除教师",key = "orgTeacherId",dict = Dict.DeleteDict)
    public Object delete(@RequestParam Integer orgTeacherId) {
        orgTeacherMapper.deleteById(orgTeacherId);
        return SUCCESS_TIP;
    }


    /**
     * 修改教师管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改教师",key ="orgTeacherId",dict = Dict.DictMap)
    public Object update(OrgTeacher orgTeacher) {
        Integer update=orgTeacherMapper.updateById(orgTeacher);
        return super.SUCCESS_TIP;
    }

    /**
     * 教师管理详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail() {
        return null;
    }

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
        //设置图片为唯一的uuid
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        try {
            //获取上传路径
            String fileSavePath = gunsProperties.getFileUploadPath();
//            Date a = new Date();
//            String b = a.toString();
//            String fileSavePath1 = fileSavePath + b +"\\";
            /**
             * transferTo在开发Web应用程序时比较常见的功能之一，
             * 就是允许用户利用multipart请求将本地文件上传到服务器,
             * Spring通过对ServletAPI的HttpServletRequest接口进行扩展，使其能够很好地处理文件上传
             */
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return pictureName;
    }


    /**
     * 根据id获取教师名称
     */
    @RequestMapping(value = "/getTeacherName")
    @ResponseBody
    public Object getTeacherName(String ids) {
        if(null == ids) return null ;
        List<String> listIds = Arrays.asList(ids.split(","));
        String teacherName = "";
        for (String id:listIds) {
            teacherName = teacherName + orgTeacherMapper.selectById(id).getTeacherName() + ",";
        }
        if("" != teacherName){
            teacherName = teacherName.substring(0,teacherName.length()-1);
        }
        return teacherName;
    }

    /**
     * 选择教师页
     * @return
     */
    @RequestMapping(value = "/chooseTeacher")
    public Object chooseTeacher() {
        return PREFIX + "kid.html";
    }

    /**
     * 选择教师列表数据
     */
    @RequestMapping(value = "/orgTeacherList")
    @ResponseBody
    public Object orgTeacherList() {
        Object orgTeacherList = this.list();
        return orgTeacherList;
    }

}
